<template>
  <div id="spaceManagePage" class="space-manage-container">
    <a-flex justify="space-between">
      <h2>空间管理</h2>

      <a-flex justify="space-between">
        <h2>空间管理</h2>
        <a-space>
          <a-button type="primary" href="/add_space" target="_blank">+ 创建空间</a-button>
        </a-space>
      </a-flex>


    </a-flex>
    <div style="margin-bottom: 16px"/>

    <!-- 搜索表单 -->
    <div class="search-form-container">
      <a-form layout="inline" :model="searchParams" @finish="doSearch">
        <a-form-item label="空间名称" name="spaceName">
          <a-input v-model:value="searchParams.spaceName" placeholder="请输入空间名称" allow-clear />
        </a-form-item>
        <a-form-item label="空间级别" name="spaceLevel">
          <a-select
            v-model:value="searchParams.spaceLevel"
            :options="SPACE_LEVEL_OPTIONS"
            placeholder="请输入空间级别"
            style="min-width: 180px"
            allow-clear
          />
        </a-form-item>
        <!-- 空间类别 -->
        <a-form-item label="空间类别" name="spaceType">
          <a-select
            v-model:value="searchParams.spaceType"
            :options="SPACE_TYPE_OPTIONS"
            placeholder="请输入空间类别"
            style="min-width: 180px"
            allow-clear
          />
        </a-form-item>



        <a-form-item label="用户 id" name="userId">
          <a-input v-model:value="searchParams.userId" placeholder="请输入用户 id" allow-clear />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </a-form-item>
        <a-space>
          <a-button type="primary" href="/add_space" target="_blank">+ 创建空间</a-button>
          <a-button type="primary" ghost href="/space_analyze?queryPublic=1" target="_blank">
            分析公共图库
          </a-button>
          <a-button type="primary" ghost href="/space_analyze?queryAll=1" target="_blank">
            分析全空间
          </a-button>
        </a-space>

      </a-form>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="dataList"
        :pagination="pagination"
        :loading="loading"
        @change="doTableChange"
        :locale="locale"
        :bordered="true"
        :row-key="(record) => record.id"
        class="space-table"
      >
        <template #bodyCell="{ column, record }">
          <!-- 空间级别 -->
          <template v-if="column.dataIndex === 'spaceLevel'">
            <a-tag>{{ SPACE_LEVEL_MAP[record.spaceLevel] }}</a-tag>
          </template>
          <!-- 空间类别 -->
          <template v-if="column.dataIndex === 'spaceType'">
            <a-tag>{{ SPACE_TYPE_MAP[record.spaceType] }}</a-tag>
          </template>

          <!-- 使用情况 -->
          <template v-if="column.dataIndex === 'spaceUseInfo'">
            <div>大小：{{ formatSize(record.totalSize) }} / {{ formatSize(record.maxSize) }}</div>
            <div>数量：{{ record.totalCount }} / {{ record.maxCount }}</div>
          </template>
          <template v-else-if="column.dataIndex === 'createTime'">
            {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template v-else-if="column.dataIndex === 'editTime'">
            {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space wrap>
              <a-button type="link" :href="`/space_analyze?spaceId=${record.id}`" target="_blank">
                分析
              </a-button>
              <a-button type="link" :href="`/add_space?id=${record.id}`" target="_blank">
                编辑
              </a-button>
              <a-button danger @click="doDelete(record.id)">删除</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import {
  deleteSpaceUsingPost,
  listSpaceByPageUsingPost,
  editSpaceUsingPost,

} from '@/api/spaceController.ts'
import dayjs from 'dayjs'
import { SPACE_LEVEL_MAP, SPACE_LEVEL_OPTIONS, SPACE_TYPE_MAP, SPACE_TYPE_OPTIONS } from '@/constants/space.ts'
import { formatSize } from '@/utils'
// 添加中文语言配置
const locale = {
  filterTitle: '筛选',
  filterConfirm: '确定',
  filterReset: '重置',
  filterEmptyText: '无筛选项',
  selectAll: '全选当页',
  selectInvert: '反选当页',
  selectionAll: '全选所有',
  sortTitle: '排序',
  expand: '展开行',
  collapse: '关闭行',
  triggerDesc: '点击降序',
  triggerAsc: '点击升序',
  cancelSort: '取消排序',
  emptyText: '暂无数据',
}

// 表格列配置
const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '空间名称',
    dataIndex: 'spaceName',
  },
  {
    title: '空间级别',
    dataIndex: 'spaceLevel',
  },
  {
    title: '空间类别',
    dataIndex: 'spaceType',
  },

  {
    title: '使用情况',
    dataIndex: 'spaceUseInfo',
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    width: 80,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]


// 数据相关
const dataList = ref([])
const total = ref(0)
const loading = ref(false)

// 搜索条件
const searchParams = reactive<API.SpaceQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) =>
      `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    pageSizeOptions: ['10', '20', '50', '100'],
  }
})


// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const res = await listSpaceByPageUsingPost({
      ...searchParams,
    })
    if (res.data.code === 0 && res.data.data) {
      dataList.value = res.data.data.records ?? []
      total.value = res.data.data.total ?? 0
    } else {
      message.error('获取数据失败：' + (res.data.message || '未知错误'))
      dataList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    message.error('获取数据失败，请稍后重试')
    dataList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 删除空间
const doDelete = async (id: number) => {
  try {
    const res = await deleteSpaceUsingPost({ id })
    if (res.data.code === 0) {
      message.success('删除成功')
      // 如果当前页没有数据了，回到上一页
      if (dataList.value.length === 1 && searchParams.current > 1) {
        searchParams.current -= 1
      }
      await fetchData()
    } else {
      message.error('删除失败：' + (res.data.message || '未知错误'))
    }
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败，请稍后重试')
  }
}

// 搜索处理
const doSearch = async () => {
  //重置搜索条件
  searchParams.current = 1
  await fetchData()
}

// 表格变化处理
const doTableChange = async (page: any, filters: any, sorter: any) => {
  // 处理分页
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize

  // 处理排序
  if (sorter && sorter.field) {
    searchParams.sortField = sorter.field
    searchParams.sortOrder = sorter.order === 'ascend' ? 'ascend' : 'descend'
  }

  await fetchData()
}

// 防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: any = null
  return function (...args: any[]) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 搜索防抖处理
const handleSearch = debounce(async () => {
  searchParams.current = 1
  await fetchData()
}, 500)


// 编辑相关状态
const editModalVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref()
const editForm = reactive({
  id: 0,
  name: '',
  introduction: '',
  category: '',
  tags: [] as string[],
})


// 页面加载时获取数据
onMounted(async () => {
  // 再获取空间数据
  await fetchData()
})
</script>

<style scoped>
.space-manage-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.search-form-container {
  background-color: #fff;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 16px;
}

.table-container {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.space-table {
  margin-top: 16px;
}


/* 操作按钮样式修复 */
:deep(.ant-space) {
  flex-wrap: wrap;
}

:deep(.ant-space-item) {
  margin-bottom: 4px;
}

/* 通过和拒绝按钮样式 */
:deep(.ant-btn-link) {
  padding: 4px 8px;
  height: auto;
  line-height: 1.4;
  font-size: 12px;
  border-radius: 4px;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 48px;
}

:deep(.ant-btn-link:not(.ant-btn-dangerous)) {
  color: #52c41a;
  border: 1px solid transparent;
}

:deep(.ant-btn-link:not(.ant-btn-dangerous):hover) {
  color: #389e0d;
  background-color: #f6ffed;
  border-color: #b7eb8f;
}

:deep(.ant-btn-link.ant-btn-dangerous) {
  color: #ff4d4f;
  border: 1px solid transparent;
}

:deep(.ant-btn-link.ant-btn-dangerous:hover) {
  color: #cf1322;
  background-color: #fff2f0;
  border-color: #ffccc7;
}

/* 编辑按钮样式 */
.edit-button {
  color: #1890ff !important;
  border: 1px solid transparent !important;
  padding: 4px 8px !important;
  height: auto !important;
  line-height: 1.4 !important;
  font-size: 12px !important;
  border-radius: 4px !important;
  transition: all 0.3s !important;
  display: inline-flex !important;
  align-items: center !important;
  justify-content: center !important;
  min-width: 48px !important;
  gap: 4px !important;
}

.edit-button:hover {
  color: #096dd9 !important;
  background-color: #e6f7ff !important;
  border-color: #91d5ff !important;
  transform: none !important;
}

/* 删除按钮样式 */
.delete-button {
  color: #ff4d4f !important;
  border: 1px solid transparent !important;
  padding: 4px 8px !important;
  height: auto !important;
  line-height: 1.4 !important;
  font-size: 12px !important;
  border-radius: 4px !important;
  transition: all 0.3s !important;
  display: inline-flex !important;
  align-items: center !important;
  justify-content: center !important;
  min-width: 48px !important;
  gap: 4px !important;
}

.delete-button:hover {
  color: #cf1322 !important;
  background-color: #fff2f0 !important;
  border-color: #ffccc7 !important;
  transform: none !important;
}

/* 按钮图标样式 */
:deep(.ant-btn .anticon) {
  font-size: 12px;
}

/* 重置按钮样式 */
.reset-button {
  margin-left: 8px;
  color: #666;
  border-color: #d9d9d9;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 15px;
  height: 32px;
  border-radius: 6px;
  font-size: 14px;
  background: linear-gradient(to bottom, #ffffff, #f5f5f5);
  box-shadow: 0 2px 0 rgba(0, 0, 0, 0.02);
  border: 1px solid #d9d9d9;
}

.reset-button:hover {
  color: #1890ff;
  border-color: #1890ff;
  background: linear-gradient(to bottom, #ffffff, #e6f7ff);
  box-shadow: 0 2px 6px rgba(24, 144, 255, 0.1);
}

.reset-button:active {
  color: #096dd9;
  border-color: #096dd9;
  background: linear-gradient(to bottom, #e6f7ff, #bae7ff);
  box-shadow: 0 1px 2px rgba(24, 144, 255, 0.2);
}

.reset-button :deep(.anticon) {
  font-size: 14px;
  transition: all 0.3s;
  color: #8c8c8c;
}

.reset-button:hover :deep(.anticon) {
  transform: rotate(180deg);
  color: #1890ff;
}

.reset-button:active :deep(.anticon) {
  color: #096dd9;
}

/* 表格样式优化 */
:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 600;
  text-align: center;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5;
}

:deep(.ant-table-tbody > tr > td) {
  text-align: center;
  vertical-align: middle;
}

:deep(.ant-table-cell) {
  padding: 12px 8px;
}

/* 操作列特殊处理 */
:deep(.ant-table-tbody > tr > td:last-child) {
  padding: 8px 4px;
}

:deep(.ant-table-tbody > tr > td:last-child .ant-space) {
  justify-content: center;
  gap: 4px !important;
}

/* 分页样式 */
:deep(.ant-pagination) {
  margin-top: 16px;
  text-align: center;
}

:deep(.ant-pagination-item-active) {
  border-color: #1890ff;
}

:deep(.ant-pagination-item-active a) {
  color: #1890ff;
}

/* 模态框样式优化 */
:deep(.ant-modal-content) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.ant-modal-header) {
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 24px;
}

:deep(.ant-modal-title) {
  font-weight: 600;
  color: #262626;
}

:deep(.ant-modal-body) {
  padding: 24px;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
  color: #262626;
}

:deep(.ant-input),
:deep(.ant-input-textarea),
:deep(.ant-select-selector) {
  border-radius: 6px;
  border-color: #d9d9d9;
  transition: all 0.3s;
}

:deep(.ant-input:hover),
:deep(.ant-input-textarea:hover),
:deep(.ant-select-selector:hover) {
  border-color: #40a9ff;
}

:deep(.ant-input:focus),
:deep(.ant-input-textarea:focus),
:deep(.ant-select-focused .ant-select-selector) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 空间样式 */
:deep(.ant-image) {
  border-radius: 4px;
  overflow: hidden;
}

/* 标签样式 */
:deep(.ant-tag) {
  margin-bottom: 4px;
  border-radius: 4px;
}

/* 空状态样式 */
:deep(.ant-empty) {
  margin: 40px 0;
}

/* 加载状态样式 */
:deep(.ant-spin-container) {
  min-height: 200px;
}

/* 搜索表单优化 */
:deep(.ant-form-inline .ant-form-item) {
  margin-right: 16px;
  margin-bottom: 16px;
}

:deep(.ant-form-inline .ant-form-item:last-child) {
  margin-right: 0;
}

/* 选择器样式优化 */
:deep(.ant-select-selector) {
  border-radius: 6px;
}

:deep(.ant-select-multiple .ant-select-selection-item) {
  border-radius: 4px;
  background-color: #f0f2f5;
  border-color: #d9d9d9;
}

:deep(.ant-select-multiple .ant-select-selection-item-remove) {
  color: #999;
}

:deep(.ant-select-multiple .ant-select-selection-item-remove:hover) {
  color: #ff4d4f;
}

/* 下拉选项样式 */
:deep(.ant-select-dropdown) {
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.ant-select-item-option-selected:not(.ant-select-item-option-disabled)) {
  background-color: #e6f7ff;
  color: #1890ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .space-manage-container {
    padding: 16px;
  }

  .search-form-container,
  .table-container {
    padding: 16px;
  }

  :deep(.ant-form-inline .ant-form-item) {
    margin-bottom: 16px;
  }

  :deep(.ant-table-scroll) {
    overflow-x: auto;
  }

  /* 移动端操作按钮优化 */
  :deep(.ant-space) {
    flex-direction: column;
    align-items: stretch;
    gap: 4px !important;
  }

  :deep(.ant-space-item) {
    width: 100%;
  }

  .edit-button,
  .delete-button,
  :deep(.ant-btn-link) {
    width: 100% !important;
    text-align: center !important;
    justify-content: center !important;
  }
}

/* Popconfirm 样式优化 */
:deep(.ant-popover-content) {
  border-radius: 6px;
}

:deep(.ant-popover-inner-content) {
  padding: 12px 16px;
}

/* 审核信息显示优化 */
.review-info {
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 16px;
  margin-top: 16px;
  border-left: 4px solid #1890ff;
}

.review-info p {
  margin-bottom: 8px;
  color: #595959;
}

.review-info p:last-child {
  margin-bottom: 0;
}
</style>
